//index.js
//获取应用实例
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
var isDealer = 0
import {
  getGoodsDetail,
  getGoodsSku
} from '../../api/goods'
import {
  addCart
} from '../../api/cart'
import {
  getComment,
  getCommentNum
} from '../../api/evaluation'
Page({
  data: {
    autoplay: true,
    interval: 10000,
    duration: 500,
    goodsDetail: {},
    standard: [],
    standardPrice: '',
    vipStandardPrice: '',
    swiperCurrent: 0,
    hasMoreSelect: false,
    selectSize: "选择规格：",
    selectSizePrice: 0,
    shopNum: 0,
    ShopPopup: false,
    ensureShow: false,
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,
    favicon: 0,
    selectptPrice: 0,
    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    wxlogin: true,
    sharecode: true,
    sharebox: true,
    title: "商品详情",
    barBg: 'red',
    color: '#ffffff',
    clickIdx: 0,
    showBuy: true,
    pics: ['https://mallcdn.oss-cn-beijing.aliyuncs.com/15887841642300416.png', 'https://mallcdn.oss-cn-beijing.aliyuncs.com/15887841481753600.png'],
    skuId: '',
    duration2: 300,
    show: false,
    customStyle: '',
    overlayStyle: '',
    skuPic: '',
    commentNum: 0
  },
  back() {
    wx.navigateBack({
      delta: 1,
      complete: res => {
        console.log(res)
      }
    })
  },
  goToList(){
    wx.navigateTo({
      url: `../comment/commentList?goodsId=${this.data.goodsId}`,
    })
  },
  popup(e) {
    let duration = this.data.duration
    this.setData({
      show: true,
      param: true,
      ShopPopup: false,
      ensureShow: false,
      duration
    })
  },
  ensurePopup(e) {
    let duration = this.data.duration
    this.setData({
      show: true,
      param: false,
      ShopPopup: false,
      ensureShow: true,
      duration
    })
  },
  exit() {
    this.setData({
      show: false
    })
  },
  onBeforeEnter(res) {},
  onEnter(res) {},
  onAfterEnter(res) {},
  onBeforeLeave(res) {},
  onLeave(res) {},
  onAfterLeave(res) {
    this.setData({
      buyNumber: 1
    })
  },

  onClickOverlay(res) {

  },
  goToCart() {
    wx.navigateTo({
      url: '/pages/cart/cart',
    })
  },
  // 预览图片
  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.id,
      urls: e.currentTarget.dataset.urls
    })
  },
  //事件处理函数
  swiperchange: function (e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  // 获取商品信息
  async getData() {
    let that = this
    let res = await getGoodsDetail(this.data.goodsId, wx.getStorageSync('access_token'))
    console.log(res)
    let standard = res.data.skuList
    console.log(standard)
    standard.forEach(it => {
      it.active = false
    })
    // if( res.data.qualityAssurance ){
    //   res.data.qualityAssurance = JSON.parse(res.data.qualityAssurance)
    // }
    
    this.setData({
      goodsDetail: res.data,
      standard
    })
    WxParse.wxParse('article', 'html', this.data.goodsDetail.intro, that, 5)
    if(wx.getStorageSync('access_token')){
      let res = await getComment(this.data.goodsId, '', 1, wx.getStorageSync('access_token'))
      console.log(res)
      if( res && res.code == 10000 ){
        this.setData({
          commentList: res.data.records.map(item => {
            if(item.images){
              item.images = item.images.split(',')
            }
            return item
          })
        })
        console.log(this.data.commentList)
      }
      let resp = await getCommentNum(this.data.goodsId, wx.getStorageSync('access_token'))
      console.log(resp)
      if( resp && resp.code == 10000 ){
        this.setData({
          commentNum: resp.data.all
        })
      }
    }
   
  },
  onLoad: function (e) {
    var that = this;
    this.setData({
      statusBarHeight: app.globalData.statusBarHeight,
      titleBarHeight: app.globalData.titleBarHeight,
      goodsId: e.id
    })
    console.log(e)
    wx.hideShareMenu()
    // if (e.isDealer == 1) {
    //   isDealer = 1
    // } else {
    //   isDealer = 0
    // }
    // 获取商品详情

    // 商品规格

    this.reputation(that.data.id);
  },
  async showParam() {
    let data = await getData()
  },

  changeBuyNumber(e) {
    this.setData({
      buyNumber: e.detail.value
    })
  },
  toAddShopCar: function () {
    if (!wx.getStorageSync('access_token')) {
      wx.showModal({
        title: '请先登录',
        content: '',
        showCancel: false,
        success: (res) => {
          wx.reLaunch({
            url: '../my/my' //返回上一级页面
          })
        }
      })
      return
    }
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    if (!that.data.standard || that.data.standard.length <= 0) {
      wx.showModal({
        content: '商品还没有规格'
      })
      return;
    }
    var childs = that.data.standard
    for (var i = 0; i < childs.length; i++) {
      that.data.standard[i].active = false
    }
    that.data.standard[0].active = true
    this.setData({
      shopType: "addShopCar",
      standardPrice: this.data.standard[0].price,
      vipStandardPrice: this.data.standard[0].vipPrice,
      skuId: this.data.standard[0].id,
      skuPic: that.data.standard[0].original,
    })
    this.data.standard[0].active = true
    this.setData({
      standard: this.data.standard,
      canSubmit: true
    })
    this.bindGuiGeTap();
  },
  tobuy: function () {
    if (!wx.getStorageSync('access_token')) {
      wx.showModal({
        title: '请先登录',
        content: '',
        showCancel: false,
        success: (res) => {
          wx.reLaunch({
            url: '../my/my' //返回上一级页面
          })
        }
      })
      return
    }
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    if (!that.data.standard || that.data.standard.length <= 0) {
      wx.showModal({
        content: '商品还没有规格'
      })
      return;
    }
    var childs = that.data.standard;
    for (var i = 0; i < childs.length; i++) {
      that.data.standard[i].active = false;
    }
    this.setData({
      shopType: "tobuy",
      standardPrice: this.data.standard[0].price,
      vipStandardPrice: this.data.standard[0].vipPrice,
    });
    this.data.standard[0].active = true
    this.setData({
      standard: this.data.standard,
      canSubmit: true,
      skuId: this.data.standard[0].id,
      skuPic: that.data.standard[0].original,
    })
    this.bindGuiGeTap();
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function () {
    this.setData({
      ShopPopup: true,
      show: true,
      ensureShow: false,
      param: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function () {
    this.setData({
      ShopPopup: false,
      show: false
    })
  },
  numJianTap: function () {
    if (this.data.buyNumber > 1) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function () {
    // if (this.data.buyNumber < this.data.buyNumMax) {
    var currentNum = this.data.buyNumber;
    currentNum++;
    this.setData({
      buyNumber: currentNum
    })
    // }
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function (e) {
    var that = this;
    // 取消该分类下的子栏目所有的选中状态
    var childs = that.data.standard;
    for (var i = 0; i < childs.length; i++) {
      that.data.standard[i].active = false;
    }
    // 设置当前选中状态
    that.data.standard[e.currentTarget.dataset.propertyindex].active = true
    that.setData({
      standardPrice: that.data.standard[e.currentTarget.dataset.propertyindex].price,
      vipStandardPrice: that.data.standard[e.currentTarget.dataset.propertyindex].vipPrice,
      skuId: that.data.standard[e.currentTarget.dataset.propertyindex].id,
      skuPic: that.data.standard[e.currentTarget.dataset.propertyindex].original,
      buyNumber: 1
    })
    console.log(that.data.standard)
    // 获取所有的选中规格尺寸数据
    var curSelectNum = 0;
    var propertyChildIds = "";
    var propertyChildNames = "";
    childs = that.data.standard;
    for (var i = 0; i < childs.length; i++) {
      if (childs[i].active) {
        curSelectNum++;
        propertyChildIds = propertyChildIds + that.data.standard[i].id;
        propertyChildNames = propertyChildNames + that.data.standard[i].simpleSpecs;
      }
    }
    var canSubmit = false;
    if (curSelectNum > 0) {
      canSubmit = true;
    }
    this.setData({
      standard: that.data.standard,
      canSubmit: canSubmit
    })
  },
  /**
   * 加入购物车
   */
  async addShopCar() {
    if (!this.data.canSubmit) {
      wx.showModal({
        title: '提示',
        content: '请选择商品规格！',
        showCancel: false
      })
      return;
    }
    if (this.data.buyNumber < 1) {
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return;
    }
    let data = {
      skuId: this.data.skuId,
      num: Number(this.data.buyNumber),
      cartType: 'CART'
    }
    let res = await addCart(data, wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {
      this.closePopupTap()
      wx.showToast({
        title: '加入购物车成功',
        icon: 'success',
        duration: 2000
      })
    } else {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false
      })
    }
    // if (this.data.standard && this.data.canSubmit) {
    //   let standard = this.data.standard.find(item => item.active);
    //   // this.bindGuiGeTap();
    //   app.postForm("/cart/insert_cart", {
    //     CustId: app.globalData.uid,
    //     GoodsId: this.data.goodsDetail.Id,
    //     StandardId: standard.Id,
    //     Num: this.data.buyNumber,
    //     ShopId: app.globalData.shopId,
    //     GoodsLibId: this.data.goodsDetail.GoodsLibId
    //   }, function (res) {
    //     console.log(res);
    //     if (res && res.code == '0') {
    //       _this.closePopupTap();
    //       wx.showToast({
    //         title: '加入购物车成功',
    //         icon: 'success',
    //         duration: 2000
    //       })
    //     } else {
    //       wx.showModal({
    //         title: '提示',
    //         content: res.msg,
    //         showCancel: false
    //       })
    //     }
    //   })
    //   return;
    // }

  },
  /**
   * 立即购买
   */
  async buyNow() {
    var that = this;
    if (!that.data.canSubmit) {
      wx.showModal({
        title: '提示',
        content: '请选择商品规格！',
        showCancel: false
      })
      return
    }
    if (that.data.buyNumber < 1) {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '购买数量不能为0！',
        showCancel: false
      })
      return
    }
    let data = {
      skuId: this.data.skuId,
      num: Number(this.data.buyNumber),
      cartType: 'BUY_NOW'
    }
    let res = await addCart(data, wx.getStorageSync('access_token'))
    console.log(res)
    if (res && res.code == 10000) {

      wx.navigateTo({
        url: `../pay-order/pay-order?orderType=BUY_NOW`,
      })
    } else {
      wx.showModal({
        title: '提示',
        content: res.msg,
        showCancel: false
      })
    }
  },
  /**
   * 组建购物车信息
   */
  bulidShopCarInfo: function () {
    // 加入购物车
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.goodsDetail.basicInfo.id;
    shopCarMap.pic = this.data.goodsDetail.basicInfo.pic;
    shopCarMap.name = this.data.goodsDetail.basicInfo.name;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    shopCarMap.logistics = this.data.goodsDetail.logistics;
    shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var shopCarInfo = this.data.shopCarInfo;
    if (!shopCarInfo.shopNum) {
      shopCarInfo.shopNum = 0;
    }
    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];
      if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.buyNumber;
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {
      shopCarInfo.shopList.push(shopCarMap);
    }
    return shopCarInfo;
  },
  /**
   * 组建立即购买信息
   */
  buliduBuyNowInfo: function () {
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.goodsDetail.basicInfo.id;
    shopCarMap.pic = this.data.goodsDetail.basicInfo.pic;
    shopCarMap.name = this.data.goodsDetail.basicInfo.name;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    shopCarMap.logistics = this.data.goodsDetail.logistics;
    shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }
    buyNowInfo.shopList.push(shopCarMap);
    return buyNowInfo;
  },
  bulidupingTuanInfo: function () {
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.goodsDetail.basicInfo.id;
    shopCarMap.pingtuanId = this.data.pingtuanOpenId;
    shopCarMap.pic = this.data.goodsDetail.basicInfo.pic;
    shopCarMap.name = this.data.goodsDetail.basicInfo.name;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectptPrice;
    //this.data.goodsDetail.basicInfo.pingtuanPrice;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    shopCarMap.logistics = this.data.goodsDetail.logistics;
    shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }
    buyNowInfo.shopList.push(shopCarMap);
    return buyNowInfo;
  },
  onShareAppMessage: function () {
    var that = this;
    that.setData({
      sharebox: true
    })
    return {
      title: this.data.goodsDetail.basicInfo.name,
      path: '/pages/goods-detail/goods-detail?id=' + this.data.goodsDetail.basicInfo.id + '&inviter_id=' + app.globalData.uid + '&share=1',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  reputation: function (goodsId) {
    var that = this;
    wx.request({
      url: app.siteInfo.url + app.siteInfo.subDomain + '/shop/goods/reputation',
      data: {
        goodsId: goodsId
      },
      success: function (res) {
        if (res.data.code == 0) {
          //console.log(res.data.data);
          that.setData({
            reputation: res.data.data
          });
        }
      }
    })
  },
  getfav: function () {
    //console.log(e)
    var that = this;
    var id = that.data.id
    wx.request({
      url: app.globalData.urls + '/shop/goods/fav/list',
      data: {
        //nameLike: this.data.goodsDetail.basicInfo.name,
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0 && res.data.data.length) {
          for (var i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].goodsId == parseInt(id)) {
              that.setData({
                favicon: 1
              });
              break;
            }
          }
        }
      }
    })
  },
  fav: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/shop/goods/fav/add',
      data: {
        goodsId: this.data.goodsDetail.basicInfo.id,
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '收藏成功',
            icon: 'success',
            image: '../../images/active.png',
            duration: 2000
          })
          that.setData({
            favicon: 1
          });
        }
      }
    })
  },
  del: function () {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/shop/goods/fav/delete',
      data: {
        goodsId: this.data.goodsDetail.basicInfo.id,
        token: app.globalData.token
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.showToast({
            title: '取消收藏',
            icon: 'success',
            image: '../../images/error.png',
            duration: 2000
          })
          that.setData({
            favicon: 0
          });
        }
      }
    })
  },
  getVideoSrc: function (videoId) {
    var that = this;
    wx.request({
      url: app.globalData.urls + '/media/video/detail',
      data: {
        videoId: videoId
      },
      success: function (res) {
        if (res.data.code == 0) {
          that.setData({
            videoMp4Src: res.data.data.fdMp4
          });
        }
      }
    })
  },
  gohome: function () {
    wx.switchTab({
      url: "/pages/index/index"
    })
  },
  tabFun: function (e) {
    var _datasetId = e.target.dataset.id;
    var _obj = {};
    _obj.curHdIndex = _datasetId;
    _obj.curBdIndex = _datasetId;
    this.setData({
      tabArr: _obj
    });
  },
  addPingTuan: function (e) {
    var id = e.currentTarget.dataset.id;
    var pid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: "/pages/pingtuan/index?id=" + id + "&uid=" + pid + "&gid=" + this.data.goodsDetail.basicInfo.id
    })
  },
  goPingtuanTap: function () {
    wx.navigateTo({
      url: "/pages/pingtuan/index?id=" + this.data.ptuanCt + "&uid=" + app.globalData.uid + "&gid=" + this.data.goodsDetail.basicInfo.id
    })
  },
  onPullDownRefresh: function (e) {
    var that = this;
    that.goPingtuan();
    that.goPingList();
    wx.stopPullDownRefresh();
  },
  onShow: function () {
    var that = this
    this.setData({
      show: false,
    })
    that.getData()
  },
  userlogin: function (e) {
    var that = this;
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    wx.login({
      success: function (wxs) {
        wx.request({
          url: app.globalData.urls + '/user/wxapp/register/complex',
          data: {
            code: wxs.code,
            encryptedData: encryptedData,
            iv: iv
          },
          success: function (res) {
            if (res.data.code != 0) {
              wx.showModal({
                title: '温馨提示',
                content: '需要您的授权，才能正常使用哦～',
                showCancel: false,
                success: function (res) {}
              })
            } else {
              that.setData({
                wxlogin: true
              })
              app.login();
              wx.showToast({
                title: '授权成功',
                duration: 2000
              })
              app.globalData.usinfo = 1;
            }
          }
        })
      }
    })
  },
  getShareBox: function () {
    this.setData({
      sharebox: false
    })
  },
  getcode: function () {
    var that = this;
    wx.showLoading({
      title: '生成中...',
    })
    wx.request({
      url: app.globalData.urls + '/qrcode/wxa/unlimit',
      data: {
        scene: "i=" + that.data.goodsDetail.basicInfo.id + ",u=" + app.globalData.uid + ",s=1",
        page: "pages/goods-detail/goods-detail",
        expireHours: 1
      },
      success: function (res) {
        if (res.data.code == 0) {
          wx.downloadFile({
            url: res.data.data,
            success: function (res) {
              wx.hideLoading()
              that.setData({
                codeimg: res.tempFilePath,
                sharecode: false,
                sharebox: true
              });
            }
          })
        }
      }
    });
  },
  savecode: function () {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.codeimg,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
    that.setData({
      sharecode: true,
    })
  },
  closeshare: function () {
    this.setData({
      sharebox: true,
      sharecode: true
    })
  },
})